package com.prototype.view.background {
	
	import flash.display.BitmapData;
	import flash.display.Graphics;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Matrix;
	
	/**
	 * ...
	 * @author Santiago.J.Elizalde
	 */
	public class TiledBackground extends Sprite {
		
		private var tile:BitmapData;
		
		private var buffer:BitmapData;
		private var matrix:Matrix
		private var _tileScale:Number = 1;
		
		public function TiledBackground() {
			tile = new BMPGroundTile02();
			addEventListener(Event.ADDED_TO_STAGE, initialize);
		}
		
		private function initialize(e:Event):void {
			removeEventListener(Event.ADDED_TO_STAGE, initialize);
			
			matrix = this.transform.matrix.clone();
			
			buffer = new BitmapData(tile.width, tile.height, true);
			buffer.draw(tile);
			
			render();
		}
		
		private function render():void {
			graphics.clear();
			graphics.beginBitmapFill(buffer, matrix, true, true);
			graphics.drawRect(0, 0, stage.stageWidth, buffer.height);
		}
		
		public function set tileScale(value:Number):void {
			this._tileScale = value;
			var scaleMatrix:Matrix = new Matrix();
			scaleMatrix.scale(value, value);
			buffer = new BitmapData(tile.width * tileScale, tile.height * tileScale, true);
			buffer.draw(tile, scaleMatrix);
			render();
		}
		
		public function get tileScale():Number {
			return _tileScale;
		}
		
		public function moveBy(value:int):void {
			matrix.translate(value, 0);
			render();
		}
	}
}